<?php
	function get_uri()
	{
	    return preg_replace('#\?.*$#D', '', $_SERVER['REQUEST_URI']);
	}
	
	function getDomain()
	{
	    GLOBAL $config;
	    return $config['base_url'];
	}
	
	function getQueryString()
	{
		return preg_replace('#^[^?]*\??#', '', $_SERVER['REQUEST_URI']);
	}
	
	function getWithQueryString()
	{
		return $_SERVER['REQUEST_URI'];
	}
	
	
	function makeFriendly($string, $max_length=NULL, $delimiter=NULL)
	{
		// This allows omitting the max length, but including a delimiter
		if ($max_length && !is_numeric($max_length)) {
			$delimiter  = $max_length;
			$max_length = NULL;
		}

		$string = fHTML::decode(fUTF8::ascii($string));
		$string = strtolower(trim($string));
		$string = str_replace("'", '', $string);

		if (!strlen($delimiter)) {
			$delimiter = '_';
		}

		$delimiter_replacement = strtr($delimiter, array('\\' => '\\\\', '$' => '\\$'));
		$delimiter_regex       = preg_quote($delimiter, '#');

		$string = preg_replace('#[^a-z0-9\-_]+#', $delimiter_replacement, $string);
		$string = preg_replace('#' . $delimiter_regex . '{2,}#', $delimiter_replacement, $string);
		$string = preg_replace('#_-_#', '-', $string);
		$string = preg_replace('#(^' . $delimiter_regex . '+|' . $delimiter_regex . '+$)#D', '', $string);
		
		$length = strlen($string);
		if ($max_length && $length > $max_length) {
			$last_pos = strrpos($string, $delimiter, ($length - $max_length - 1) * -1);
			if ($last_pos < ceil($max_length / 2)) {
				$last_pos = $max_length;
			}
			$string = substr($string, 0, $last_pos);
		}
		
		return $string;
	}
	
	function redirect($url=NULL)
	{
		if (preg_match('#^https?://#i', $url)) {
		    $url = $url;
		} else {
		    $url = getDomain() . '/' . $url;
		}
		
		header('Location: ' . $url);
		exit($url);
	}
	
	function removeFromQueryString($parameter)
	{
		$parameters = func_get_args();
		
		parse_str(getQueryString(), $qs_array);
		if (get_magic_quotes_gpc()) {
			$qs_array = array_map('stripslashes', $qs_array);
		}
		
		foreach ($parameters as $parameter) {
			unset($qs_array[$parameter]);
		}
		
		return '?' . http_build_query($qs_array, '', '&');
	}
	
	function replaceInQueryString($parameter, $value)
	{
		parse_str(getQueryString(), $qs_array);
		if (get_magic_quotes_gpc()) {
			$qs_array = array_map('stripslashes', $qs_array);
		}
		
		settype($parameter, 'array');
		settype($value, 'array');
		
		if (sizeof($parameter) != sizeof($value)) {
			throw new fProgrammerException(
				"There are a different number of parameters and values.\nParameters:\n%1\$s\nValues\n%2\$s",
				$parameter,
				$value
			);
		}
		
		for ($i=0; $i<sizeof($parameter); $i++) {
			$qs_array[$parameter[$i]] = $value[$i];
		}
		
		return '?' . http_build_query($qs_array, '', '&');
	}